/*
 * @Date: 2022-02-24 10:01:29
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:
 * @LastEditTime: 2023-11-16 15:50:32
 * @FilePath: \go-ezcode-admin\system\core\db\dblog.go
 */
package db

import (
	"fmt"
	syslog "log"
	"os"
	"time"

	"go-ezcode-admin/system/core/config"
	"go-ezcode-admin/system/core/log"
	"gorm.io/gorm/logger"
)

type writer struct {
	logger.Writer
}

func NewWriter(w logger.Writer) *writer {
	return &writer{Writer: w}
}

//日志配置
func LogConfig() logger.Interface {
	defautLoglevel := logger.Warn

	switch config.Instance().DB.DBloglevel {
	case "silent", "close":
		defautLoglevel = logger.Silent
	case "error", "Error":
		defautLoglevel = logger.Error
	case "warn", "Warn":
		defautLoglevel = logger.Warn
	case "info", "Info":
		defautLoglevel = logger.Info
	default:
		defautLoglevel = logger.Info
	}
	return logger.New(
		NewWriter(syslog.New(os.Stdout, "\r\n", syslog.LstdFlags)), // 重载日志
		logger.Config{
			SlowThreshold:             time.Second * 2, // 慢 SQL 阈值
			LogLevel:                  defautLoglevel,  // 日志级别
			IgnoreRecordNotFoundError: true,            // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,           // 彩色打印
		},
	)
}

//重写Printf 方法
func (w *writer) Printf(message string, data ...interface{}) {
	//重写日志 输出日志文件
	go log.Intrance().Error(fmt.Sprintf(message+"\n", data...))

}
